package org.wisdom.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

/**
 * @author zhangzhiyan
 * @date 2022/05/10 14:04
 **/
@Slf4j
@Configuration
@ComponentScan(basePackages = {"org.wisdom.component","org.wisdom.service"})
public class WebConfiguration implements WebMvcConfigurer {

    @Value("#{'${cors.allowedOrigins:*}'.split(',')}")
    private List<String> allowedOrigins;
    @Value("#{'${cors.allowedHeaders:*}'.split(',')}")
    private List<String> allowedHeaders;
    @Value("#{'${cors.allowedMethods:*}'.split(',')}")
    private List<String> allowedMethods;
    @Value("${cors.corsMapping:/**}")
    private String corsMapping;

    @Bean
    public FilterRegistrationBean<CorsFilter> corsFilter() {
        log.info("跨域设置......");
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        for (String val : allowedOrigins) {
            config.addAllowedOriginPattern(val);
        }
        for (String val : allowedHeaders) {
            config.addAllowedHeader(val);
        }
        for (String val : allowedMethods) {
            config.addAllowedMethod(val);
        }
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration(corsMapping, config);

        // 项目中有多个filter时此处设置改CorsFilter的优先执行顺序
        FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<>(new CorsFilter(source));
        bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
        return bean;
    }
}
